package com.agileplex.products.acc.commands;

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

import com.agileplex.products.acc.CommandExecutionException;
import com.agileplex.products.acc.Session;
import com.agileplex.products.acc.results.CommandNotFound;
import com.agileplex.products.acc.results.ICommandResult;

/**
 * Abstract command
 *
 * @creator Rui Tang
 * @date 2008-06-18
 *
 * @LastChanged
 * @LastChangedBy $LastChangedBy: tangrui@agileplex.com $
 * @LastChangedDate $LastChangedDate: 2008-06-22 16:08:49 +0000 (Sun, 22 Jun 2008) $
 * @LastChangedRevision $LastChangedRevision: 7 $
 */
public class AbstractCommand extends Command {

    private List<Command> commands;

    public AbstractCommand(String name) {
        super(name);
        this.commands= new ArrayList<Command>(); 
    }

    public void addCommand(Command cmd) {
        this.commands.add(cmd);
    }

    public List<Command> getCommands() {
        return this.commands;
    }

    /*public ICommandResult exec(String cmdStr, Session session) throws CommandExecutionException {
        LiteralCommand literal = new LiteralCommand(cmdStr);
        List<Command> cmds = this.getCommands();
        for (Iterator<Command> it = cmds.iterator(); it.hasNext(); ) {
            Command cmd = it.next();
            if (literal.startsWith(cmd.getName())) {
                return cmd.exec(literal.getRest(cmd.getName()), session);
            }
        }

        return CommandNotFound.getSingleton();
    }*/

    public ICommandResult exec(LexicalParser lexicalParser, Session session) throws CommandExecutionException {
        String token = lexicalParser.getNextToken();
        List<Command> cmds = this.getCommands();
        for (Iterator<Command> it = cmds.iterator(); it.hasNext(); ) {
            Command cmd = it.next();
            if (token.equals(cmd.getName())) {
                return cmd.exec(lexicalParser, session);
            }
        }

        return CommandNotFound.getSingleton();
    }

}
